/**
 * @author: 王志昂
 * @create: 2014年6月5日
 * @note: 前端JS公共模块
 * @history:
 * 2014年6月5日 11:39 创建
 */
define(function (require, exports, module) {
    require('jquery');
    require('underscore');
    require("uniform")($);
    require('slimscroll')($);
    require("pop")($);
    require("select2")($);
    var datetimepicker = require("datetimepicker")($);
    var SuperbUtil = {
        handleSidebarToggler: function () {
            // handle sidebar show/hide
            $('.page-sidebar').on('click', '.sidebar-toggler', function (e) {
                var body = $('body');
                var sidebar = $('.page-sidebar');

                if ((body.hasClass("page-sidebar-hover-on") && body.hasClass('page-sidebar-fixed')) || sidebar.hasClass('page-sidebar-hovering')) {
                    body.removeClass('page-sidebar-hover-on');
                    sidebar.css('width', '').hide().show();
                    e.stopPropagation();
                    runResponsiveHandlers();
                    return;
                }

                $(".sidebar-search", sidebar).removeClass("open");

                if (body.hasClass("page-sidebar-closed")) {
                    body.removeClass("page-sidebar-closed");
                    if (body.hasClass('page-sidebar-fixed')) {
                        sidebar.css('width', '');
                    }
                } else {
                    body.addClass("page-sidebar-closed");
                }
                runResponsiveHandlers();
            });

            // handle the search bar close
            $('.page-sidebar').on('click', '.sidebar-search .remove', function (e) {
                e.preventDefault();
                $('.sidebar-search').removeClass("open");
            });

            // handle the search query submit on enter press
            $('.page-sidebar').on('keypress', '.sidebar-search input', function (e) {
                if (e.which == 13) {
                    window.location.href = "extra_search.html";
                    return false; //<---- Add this line
                }
            });

            // handle the search submit
            $('.sidebar-search .submit').on('click', function (e) {
                e.preventDefault();

                if ($('body').hasClass("page-sidebar-closed")) {
                    if ($('.sidebar-search').hasClass('open') == false) {
                        if ($('.page-sidebar-fixed').size() === 1) {
                            $('.page-sidebar .sidebar-toggler').click(); //trigger sidebar toggle button
                        }
                        $('.sidebar-search').addClass("open");
                    } else {
                        window.location.href = "extra_search.html";
                    }
                } else {
                    window.location.href = "extra_search.html";
                }
            });
        },
        handleSidebarMenu: function () {
            var self = this;
            jQuery('.page-sidebar').on('click', 'li > a', function (e) {
                if ($(this).next().hasClass('sub-menu') == false) {
                    if ($('.btn-navbar').hasClass('collapsed') == false) {
                        $('.btn-navbar').click();
                    }
                    return;
                }

                var parent = $(this).parent().parent();

                parent.children('li.open').children('a').children('.arrow').removeClass('open');
                parent.children('li.open').children('.sub-menu').slideUp(200);
                parent.children('li.open').removeClass('open');

                var sub = jQuery(this).next();
                if (sub.is(":visible")) {
                    jQuery('.arrow', jQuery(this)).removeClass("open");
                    jQuery(this).parent().removeClass("open");
                    sub.slideUp(200, function () {
                        self.handleSidebarAndContentHeight();
                    });
                } else {
                    jQuery('.arrow', jQuery(this)).addClass("open");
                    jQuery(this).parent().addClass("open");
                    sub.slideDown(200, function () {
                        self.handleSidebarAndContentHeight();
                    });
                }

                e.preventDefault();
            });

            // handle ajax links
            /**
             jQuery('.page-sidebar').on('click', ' li > a.ajaxify', function (e) {
			 e.preventDefault();
			 App.scrollTop();
			 var url = $(this).attr("href");
			 var menuContainer = jQuery('.page-sidebar ul');
			 var pageContent = $('.page-content');
			 var pageContentBody = $('.page-content .page-content-body');
			 menuContainer.children('li.active').removeClass('active');
			 menuContainer.children('arrow.open').removeClass('open');
			 $(this).parents('li').each(function () {
			 $(this).addClass('active');
			 $(this).children('a > span.arrow').addClass('open');
			 });
			 $(this).parents('li').addClass('active');
			 App.blockUI(pageContent, false);
			 $.post(url, {}, function (res) {
			 App.unblockUI(pageContent);
			 pageContentBody.html(res);
			 App.fixContentHeight(); // fix content height
			 App.initUniform(); // initialize uniform elements
			 });
			 });
             **/
        },
        handleSidebarAndContentHeight: function () {
            var content = $('.page-content');
            var sidebar = $('.page-sidebar');
            var body = $('body');
            var height;

            if (body.hasClass("page-footer-fixed") === true && body.hasClass("page-sidebar-fixed") === false) {
                var available_height = $(window).height() - $('.footer').height();
                if (content.height() < available_height) {
                    content.attr('style', 'min-height:' + available_height + 'px !important');
                }
            } else {
                if (body.hasClass('page-sidebar-fixed')) {
                    height = this._calculateFixedSidebarViewportHeight();
                } else {
                    height = sidebar.height() + 20;
                }
                if (height >= content.height()) {
                    content.attr('style', 'min-height:' + height + 'px !important');
                }
            }
        },
        _calculateFixedSidebarViewportHeight: function () {
            var sidebarHeight = $(window).height() - $('.header').height() + 1;
            if ($('body').hasClass("page-footer-fixed")) {
                sidebarHeight = sidebarHeight - $('.footer').height();
            }

            return sidebarHeight;
        },
        handleGoTop: function () {
            var self = this;
            /* set variables locally for increased performance */
            jQuery('.footer').on('click', '.go-top', function (e) {
                self.scrollTo();
                e.preventDefault();
            });
        },
        scrollTo: function (el, offeset) {
            pos = el ? el.offset().top : 0;
            jQuery('html,body').animate({
                scrollTop: pos + (offeset ? offeset : 0)
            }, 'slow');
        },
        // 来自jquery.uniform.js
        handleUniform: function () {
            if (!jQuery().uniform) {
                return;
            }
            var test = $("input[type=checkbox]:not(.toggle), input[type=radio]:not(.toggle, .star)");
            if (test.size() > 0) {
                test.each(function () {
                    if ($(this).parents(".checker").size() == 0) {
                        $(this).show();
                        $(this).uniform();
                    }
                });
            }
        },
        // 来自jquery.uniform.js
        initUniform: function (els) {
            if (els) {
                jQuery(els).each(function () {
                    if ($(this).parents(".checker").size() == 0) {
                        $(this).show();
                        $(this).uniform();
                    }
                });
            } else {
                this.handleUniform();
            }
        },
        /**
         * 驼峰转连字符
         */
        camelToLink: function (str) {
            return str.replace(/([A-Z])/g, "-$1").toLowerCase();
        },
        handleChoosenSelect: function (selectorName, width) {
            require("chosen")($);
            $(selectorName).each(function () {
                $(this).chosen({
                    search_contains: true,
                    display_width: width, //默认是220px
                    allow_single_deselect: $(this).attr("data-with-diselect") === "1" ? true : false,
                    no_results_text: '没有搜索到结果'
                });
            });
        },
        selectAll: function (selectorName, checkBoxClass) {
            $(document).on('click', selectorName, function () {
                $(checkBoxClass).prop('checked', this.checked);
            });
            $(document).on('click', checkBoxClass, function () {
                if ($(checkBoxClass).length == $(checkBoxClass + ':checked').length) {
                    $(selectorName).prop('checked', true);
                } else {
                    $(selectorName).removeAttr('checked');
                }
            });
        },
        refreshSortNumber: function (tableId, selecter) {
            tableId = tableId || '#table-list';
            selecter = selecter || "input[name='sort']";
            var trAmount = $(tableId).find('tbody tr').length;
            $(tableId).find('tbody tr').each(function () {
                $(this).find(selecter).val(trAmount);
                trAmount--;
            });
        },
        bindDragTable: function (tableId, selecter, noDragParts) {
            require("tablednd")($);
            tableId = tableId || '#table-list';
            //绑定拖动排序
            var self = this;
            $(tableId).tableDnD({
                onDragClass: "mb-drag-highlighter",
                onDrop: function (table, row) {
                    self.refreshSortNumber(tableId, selecter);
                },
                noDragParts: noDragParts
            });
        },
        recordCount: function (listSelector, countSpanSelector) {
            var list = $(listSelector);
            var length = '-';
            if (list != undefined && list.length) {
                length = list.length;
            }
            $(countSpanSelector).html(length);
        },
        getUrlParam: function (param) {
            var tmp = '';
            var currentUrl = window.location.href;
            var rs = new RegExp("(^|)" + param + "=([^\&]*)(\&|$)", "gi").exec(currentUrl);
            if (tmp = rs) {
                return tmp[2];
            }
            return '';
        },
        paginate: function (page, total) {
            if (total >= 10) {
                $('.pagination .page').hide();
                $('.pagination .page').eq(0).show();
                $('.pagination .page').eq(total - 1).show();
                if (page <= 4) {
                    $('.pagination span').eq(0).hide();
                    $('.pagination span').eq(1).show();
                    $('.pagination .page').eq(page - 1).show().prevAll('.page').show();
                    $('.pagination .page').eq(page).show();
                    $('.pagination .page').eq(page + 1).show();
                }
                else if (page > 4 && page <= total - 3) {
                    $('.pagination span').show();
                    $('.pagination .page').eq(page - 2).show();
                    $('.pagination .page').eq(page - 1).show();
                    $('.pagination .page').eq(page).show();
                } else {
                    $('.pagination span').eq(1).hide();
                    $('.pagination span').eq(0).show();
                    $('.pagination .page').eq(page - 1).show().nextAll('.page').show();
                    $('.pagination .page').eq(page - 2).show();
                    $('.pagination .page').eq(page - 3).show();
                }
            }
            $('.pagination .page').eq(page - 1).addClass('active').siblings().removeClass('active');
        },
        // 日期选择开始
        handleDatetimePicker: function () {
            $(".form_advance_datetime").datetimepicker({
                format: "yyyy-mm-dd hh:ii",
                autoclose: true,
                todayBtn: true,
                startDate: "2015-11-11 10:00",
                pickerPosition: (false ? "bottom-right" : "bottom-left"),
                minuteStep: 10
            });
        },
        /*时间格式转时间字符串*/
        timeFormat: function (time, format) {
            var time = new Date(time);
            var o = {
                "M+": time.getMonth() + 1, //month
                "d+": time.getDate(), //day
                "h+": time.getHours(), //hour
                "m+": time.getMinutes(), //minute
                "s+": time.getSeconds(), //second
                "q+": Math.floor((time.getMonth() + 3) / 3), //quarter
                "S": time.getMilliseconds() //millisecond
            };
            if (/(y+)/.test(format)) format = format.replace(RegExp.$1, (time.getFullYear() + "").substr(4 - RegExp.$1.length));
            for (var k in o)
                if (new RegExp("(" + k + ")").test(format))
                    format = format.replace(RegExp.$1,
                        RegExp.$1.length == 1 ? o[k] :
                            ("00" + o[k]).substr(("" + o[k]).length));
            return format;
        },
        /**
         * 分页控制方法
         * @param result
         * @param pageNum
         * @param searchCondition
         * @param stradegy 这是个对象，必须实现bindPageEvent！现在的页面有很多了。
         * @param callback
         * @returns {*|jQuery}
         */
        moreData: function (result, pageNum, searchCondition, stradegy, callback) {
            var page = result.data;
            if (page == null) {
                $('#content').html("暂无数据");
                $("#pageDiv").html("");
            } else {
                var data = page.content;

                if (data == null || data.length == 0) {
                    $('#content').html("暂无数据");
                    $("#pageDiv").html("");
                    return;
                }
                page.current = eval(page.number);

                if (!page.last) {
                    page.nextNum = eval(page.current + 1 + 1);
                }

                if (!page.first) {
                    page.prevNum = eval(page.current + 1 - 1);
                }
                if (page.totalPages === 0) return $("#pageDiv").html('');

                var morePageHtml = "<ul class='pagination'>";
                morePageHtml += '<li class="disabled"><a>共' + page.totalElements + '条记录</a></li>';
                var frontPrevPage = $("#front_prev_page");
                if (!page.first) {
                    morePageHtml += '<li><a class="prev_page" href="javascript:void(0)">上一页</a></li>';
                    if (frontPrevPage) {
                        frontPrevPage.removeClass("disabled").addClass("prev_page").unbind("click");
                    }
                } else {
                    morePageHtml += '<li class="disabled"><a>上一页</a></li>';
                    if (frontPrevPage) {
                        frontPrevPage.removeClass("prev_page").addClass("disabled").unbind("click");
                    }
                }
                var i = 1;
                if (page.totalPages < 10) {
                    for (; i <= page.totalPages; i++) {
                        if (i == page.number + 1) {
                            morePageHtml += '<li class="active page"><a href="javascript:;" class="page_' + i + '" href="javascript:void(0)">' + i + '</a></li>';
                        } else {
                            morePageHtml += '<li class="page"><a href="javascript:;" class="page_' + i + '" href="javascript:void(0)">' + i + '</a></li>';
                        }
                    }
                } else {
                    for (; i <= page.totalPages; i++) {
                        morePageHtml += "<li class='page'><a href='javascript:;'>" + i + "</a></li>";
                        if (i == 1 || i == page.totalPages - 1) {
                            morePageHtml += "<li><span>...</span></li>";
                        }
                    }
                }
                var frontNextPage = $("#front_next_page");
                if (!page.last) {
                    morePageHtml += '<li><a class="next_page" href="javascript:void(0)">下一页</a></li>';
                    if (frontNextPage) {
                        frontNextPage.removeClass("disabled").addClass("next_page").unbind("click");
                    }
                } else {
                    morePageHtml += '<li class="disabled"><a>下一页</a></li>';
                    if (frontNextPage) {
                        frontNextPage.removeClass("next_page").addClass("disabled").unbind("click");
                    }
                }
                morePageHtml += '<li><span>共' + page.totalPages + '页,去第 <input class="ui-page-skipTo go_page_num" type="text" value=""/> 页</span></li>';
                morePageHtml += '<li><a class="go_page" href="javascript:void(0)">跳转</a></li>';
                morePageHtml += '</ul>';
                $("#pageDiv").html(morePageHtml);
                SuperbUtil.paginate(pageNum, page.totalPages);
                $(".page", '.pagination').unbind("click").click(function () {
                    stradegy.bindPageEvent(searchCondition, parseInt($(this).text(), 10));
                });
                if (!page.first) {
                    $(".first_page").unbind("click").click(function () {
                        stradegy.bindPageEvent(searchCondition, 1);
                    });
                    $(".prev_page").unbind("click").click(function () {
                        stradegy.bindPageEvent(searchCondition, page.prevNum);
                    });
                }

                if (!page.last) {
                    $(".next_page").unbind("click").click(function () {
                        stradegy.bindPageEvent(searchCondition, page.nextNum);
                    });
                    $(".last_page").unbind("click").click(function () {
                        stradegy.bindPageEvent(searchCondition, page.totalPages);
                    });
                }

                $(".go_page").unbind("click").click(function () {
                    var goNum = parseInt($(".go_page_num").val(), 10);
                    goNum = isNaN(goNum) ? 1 : goNum;
                    stradegy.bindPageEvent(searchCondition, goNum);
                });

                if (callback) {
                    callback();
                }
            }
        }
    };
    SuperbUtil.handleDatetimePicker();

    module.exports = SuperbUtil;
});
